/**
 * 目标1：信息渲染
 *  1.1 获取用户的数据
 *  1.2 回显数据到标签上
 * */

const creator = 'lililili'
axios({
  url: 'https://hmajax.itheima.net/api/settings',
  params: {
    creator
  }
}).then(result => {
  // console.log(result.data.data);
  const userObj = result.data.data
  // console.log(Object.keys(userObj));
  Object.keys(userObj).forEach(key => {
    if (key === "avatar") {
      document.querySelector('.prew').src = userObj[key]
    } else if (key === 'gender') {
      // userObj[key].checked = true
      const gRadio = document.querySelectorAll('.gender')
      // console.log(rGetradio);
      const gNum = userObj[key]
      // console.log(gNum);
      gRadio[gNum].checked = true
    } else {
      document.querySelector(`.${key}`).value = userObj[key]
    }
  })
})

/**
 * 目标2：修改头像
 *  2.1 获取头像文件
 *  2.2 提交服务器并更新头像
 * */
document.querySelector('.upload').addEventListener('change', e => {
  console.log(e.target.files[0]);
  const bgUrl = e.target.files[0]
  const fd = new FormData()
  fd.append('avatar', bgUrl)
  fd.append('creator', creator)
  axios({
    url: 'https://hmajax.itheima.net/api/avatar',
    method: 'put',
    data: fd
  }).then(result => {
    const imgUrl = result.data.data.avatar
    document.querySelector('.prew').src = imgUrl
  })
})
/**
 * 目标3：提交表单
 *  3.1 收集表单信息
 *  3.2 提交到服务器保存
 */

document.querySelector('.submit').addEventListener('click', () => {
  // console.log(1);
  const userForm = document.querySelector('.user-form')
  const uForm = serialize(userForm, { hash: true, empty: true })

  uForm.gender = +uForm.gender
  uForm.creator = creator

  console.log(uForm);
  axios({
    url: 'https://hmajax.itheima.net/api/settings',
    method: 'put',
    data: {
      ...uForm
    }
  }).then(result => {
    console.log(result);
    const toastDom = document.querySelector('.my-toast')
    const toast = new bootstrap.Toast(toastDom)
    toast.show()
  })
})
